local Sol = LibStub("Sol");
local nkLibChannels = LibStub("nkLibChannels");
local nkLibSocial = LibStub("nkLibSocial");
local nkLibQuests = LibStub("nkLibQuests");

nkPartyQuest = {};

nkPartyQuest.AddonName = "nkPartyQuest";
nkPartyQuest.AddonVersion = "v0.6.4";

local ChannelPW = "I£i$0";
local OnUpdateDelay = 2;
local LastChannelAction = nil;

-- Hook standard to chat output

local obj = ChatFrame1;
local orig=obj["AddMessage"];

function DEFAULT_CHAT_FRAME:AddMessage(message,r,g,b)

	if nkPartyQuest.Com.ChannelName == nil then
		orig(obj, message,r,g,b); 
		return;
	end;
	 
	if (string.find (string.lower(message), string.lower(nkPartyQuest.Com.ChannelName)) ~= nil) then
		-- Only messages being sent within the custom channel are of interest	
		if (arg4 ~= UnitName("player") and UnitExists("party1")) then
			-- Only if the player is in a party messages will be checked
			if (nkLibSocial.checkPlayerInGroupOrRaid (arg4, false) ~= nil) then			
				-- Only commands send by other players currently part of your group are of interest		
				if string.find (string.lower(message), string.lower(nkPartyQuest.Com.DataPrefix.SENDALLDATA)) ~= nil or
				   string.find (string.lower(message), string.lower(nkPartyQuest.Com.DataPrefix.SENDNEWQUEST)) ~= nil or
				   string.find (string.lower(message), string.lower(nkPartyQuest.Com.DataPrefix.SENDUPDATE)) ~= nil or
				   string.find (string.lower(message), string.lower(nkPartyQuest.Com.DataPrefix.SENDCANCEL)) ~= nil then
					-- Only if prefix is found in the message it will be processed
					nkPartyQuest.Com.ProcessDataStream (arg4, arg1);
					if nkPartyQuestFrame:IsVisible() == true then  			
						nkPartyQuest.UI.UpdateUI();	
					end;
				end;
			end;
		end;	
		-- Every message where the channel name occurs is suppressed		
		return;
	end;
	orig(obj, message,r,g,b); 
end;


local orig_ReloadUI = ReloadUI;

ReloadUI = function()

	if nkPartyQuest.Com.ChannelName ~= nil and nkPartyQuest.Com.ChannelName ~= "" then
		LeaveChannel (nkPartyQuest.Com.ChannelName);
	end;

	orig_ReloadUI();

end;

----------------------------------

nkPartyQuest.SlashHandler = function (editBox, msg)	
	nkPartyQuestFrame:Show();				 	
end;


nkPartyQuest.OnLoad = function (this)
	this:RegisterEvent("PARTY_MEMBER_CHANGED");
	this:RegisterEvent("QUEST_COMPLETE");
	this:RegisterEvent("ADDNEW_QUESTBOOK");
	this:RegisterEvent("RESET_QUESTBOOK");
	this:RegisterEvent("CHAT_MSN_OPEN");
	this:RegisterEvent("CHAT_MSN_POPUP");
	this:RegisterEvent("VARIABLES_LOADED");
	
	SLASH_NKPARTYQUEST_SlashHandler1 = "/nkpartyquest";
	SLASH_NKPARTYQUEST_SlashHandler2 = "/nkpq";
	SlashCmdList["NKPARTYQUEST_SlashHandler"] = nkPartyQuest.SlashHandler;
	
	this.delayTime = OnUpdateDelay;
	this.remainingTime = this.delayTime;
	
	Sol.io.Printf (nkPartyQuest.AddonName .. " " .. nkPartyQuest.AddonVersion .. " loaded");
	Sol.io.Printf (nkPartyQuest.Lang.Common.CHATCMD);
	
end;

nkPartyQuest.OnEvent = function (this, event, ...)

	if (event == "VARIABLES_LOADED") then
		if nkLibQuests_QBase == nil then
			nkLibQuests_QBase = {};
		end;
		
		if AddonManager then
    		local addon = {
        		name = nkPartyQuest.AddonName,
        		version = nkPartyQuest.AddonVersion,
        		author = "Naifu",
        		description = "Quest information sharing.",
        		icon = "Interface/Addons/nkPartyQuest/Textures/AMIcon.tga",
        		category = "Leveling",
        		configFrame = nkPartyQuestFrame, 
        		slashCommand = "/nkpq",
        		miniButton = nkPartyQuestMiniButton,
        		--disableScript = nkMultiB.Disable,
        		--enableScript = nkMultiB.Enable,
    	}
	    	if AddonManager.RegisterAddonTable then
    	    	AddonManager.RegisterAddonTable(addon)
    		else
        		AddonManager.RegisterAddon(addon.name, addon.description, addon.icon, addon.category, 
            	addon.configFrame, addon.slashCommand, addon.miniButton, addon.version, addon.author)
    		end;
		end;
		
		if nkPartyQuest.Com.ChannelName == nil or nkPartyQuest.Com.ChannelName == "" then
			nkPartyQuest.Com.DailyChannel();
		end;				
	elseif (event == "PARTY_MEMBER_CHANGED" ) then
		nkPartyQuest.Core.HandlePartyMemberChange();
	elseif (event == "ADDNEW_QUESTBOOK") then
		local QuestID = arg1;
		local NewQuestName = nil;
		
		if QuestID ~= nil and nkLibQuests_QBase[QuestID] == nil then
			NewQuestName = nkPartyQuest.Quests.GetNewQuestName();
		end;
		
		local tmpQuestUpdates = nkPartyQuest.Quests.GetQuestUpdates();		
		
		if tmpQuestUpdates ~= nil then
			nkPartyQuest.Com.UpdateTransData(tmpQuestUpdates);
		end;

		if nkPartyQuestFrame:IsVisible() == true then  			
			nkPartyQuest.UI.UpdateUI();
		end;
		
		if QuestID ~= nil and NewQuestName ~= nil then
			-- New quest found
			nkLibQuests.AddQuestToBase(QuestID, nkLibQuests.CleanQuestName(NewQuestName));
		end;		
	elseif (event == "RESET_QUESTBOOK") or (event == "QUEST_COMPLETE") then
		local tmpQuestUpdates = nkPartyQuest.Quests.GetQuestUpdates();
		
		if tmpQuestUpdates ~= nil then
			nkPartyQuest.Com.UpdateTransData(tmpQuestUpdates);
		end;

		if nkPartyQuestFrame:IsVisible() == true then  			
			nkPartyQuest.UI.UpdateUI();
		end;
	elseif 	(event == "CHAT_MSN_OPEN" or event == "CHAT_MSN_POPUP") then
		-- If whisper is within custom channel don't show popup frame
		local CRGFrameTitle = getglobal("CRG_Chat" .. tostring(arg1) .. "_TitleText");
		if CRGFrameTitle then
			if CRGFrameTitle:GetText() == nkPartyQuest.Com.ChannelName then
		 		local CRGFrame = getglobal("CRG_Chat" .. tostring(arg1));
		 		if CRGFrame then CRGFrame:Hide(); end;
		 	end;
		end;
	end;
end;

nkPartyQuest.OnUpdate = function(this, elapsedTime)

	this.remainingTime = this.remainingTime - elapsedTime;
	
	if UnitName("player") ~= nil and nkPartyQuest.Core.QuestList[UnitName("player")] == nil then
		nkPartyQuest.Core.QuestList[UnitName("player")] = nkLibQuests.GetQuestList();
	end;	
	
	if (this.remainingTime < 0) then
	
		nkPartyQuest.Com.DailyChannel();
				
		if (nkLibChannels.IsChannelAvailable (nkPartyQuest.Com.ChannelName) == true) then
			-- Channel available		
			nkPartyQuestFrame_ChannelStatus_Info:SetText("|cff15B500" .. nkPartyQuest.Lang.Common.ONLINE .. "|r");
			
			LastChannelAction = nil;
			this.remainingTime = this.delayTime;
			
			if(UnitExists("party1") and nkPartyQuest.Com.TransferData ~= nil) then
				-- Pending information for sending due
				--DEFAULT_CHAT_FRAME:AddMessage("sending pending quest data");
				nkPartyQuest.Com.SendQuestData();
			end;
			
			return;
		else
			-- Channel not available			
			nkPartyQuestFrame_ChannelStatus_Info:SetText("|cffFF0000" .. nkPartyQuest.Lang.Common.OFFLINE .. "|r");

			if (LastChannelAction == nil or LastChannelAction == "create") then
				nkLibChannels.JoinChannel (nkPartyQuest.Com.ChannelName, ChannelPW, nil);
				LastChannelAction = "join";
			else		
				nkLibChannels.CreateChannel (nkPartyQuest.Com.ChannelName, ChannelPW);
				LastChannelAction = "create";
			end;
		
			this.remainingTime = this.delayTime;
		end;
		
		-- Leave old channels	
	end;

end;